﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.Menu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Write.Application.Handler.Menu
{
    /// <summary>
    /// 添加菜单信息请求命令处理类
    /// </summary>
    public class CreateMenuHandler:IRequestHandler<CreateMenuCommand, ApiResult<int>>
    {
        IBaseRepository<MenuModel> menuRep;
        IMapper mapper;

        public CreateMenuHandler(IBaseRepository<MenuModel> menuRep, IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(CreateMenuCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();
                var entity = menuRep.GetAll().Where(x => x.P_ID == request.p_ID && !x.IsDeleted && x.MenuName == request.menuName).FirstOrDefault();
                if (entity != null)
                {
                    res.Msg = "同一级菜单下已存在菜单名称";
                    res.Code=ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                var model=mapper.Map<MenuModel>(request);
                var paixu= menuRep.GetAll().OrderByDescending(x=>x.Id).Select(x=>x.PaiXu).FirstOrDefault();
                if(paixu==0)
                {
                    model.PaiXu = 1;
                }
                else
                {
                    model.PaiXu = paixu + 1;
                }

                model.CreateName = "王五";
                model.CreateDate = DateTime.Now;

                int r=menuRep.CreateAsync(model).Result;
                if(r>0)
                {
                    res.Msg = "菜单创建成功";
                    res.Code=ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "菜单创建失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
